package com.feijin.testwisdomzonedemo.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.feijin.testwisdomzonedemo.R;
import com.lgc.garylianglib.util.L;
import com.lgc.garylianglib.util.base.BaseActivity;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.view.KeyEvent.KEYCODE_BACK;

/**
 * <pre>
 *     author : feijin_lgc
 *     e-mail : 595184932@qq.com
 *     time   : 2018/4/24 下午3:37
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class WebViewActivity extends BaseActivity {
    private static String TAG = "WebViewActivity";

    @BindView(R.id.detail_webview)
    WebView mWebView;

    public static final String TITLE = "title";// 标题
    public String URL = "";
    public static final String TYPE = "type";
    private static ValueCallback<Uri> mUploadMessage;
    private Uri photoUri;// 图片地址
    private String mCameraFilePath;
    private final static int FILECHOOSER_RESULTCODE = 1;
    private View parentView;
    private ArrayList<String> loadHistoryUrls = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parentView = getLayoutInflater().inflate(R.layout.activity_main, null);
        setContentView(parentView);
        ButterKnife.bind(this);
        init();
        initView();
    }

    @Override
    protected void init() {
        super.init();
        URL = getIntent().getStringExtra("URL");
    }

    @Override
    protected void initView() {
        super.initView();


        // 设置可以支持缩放
        mWebView.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        mWebView.getSettings().setBuiltInZoomControls(false);
        // 扩大比例的缩放
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.SINGLE_COLUMN);


        WebSettings webSettings = mWebView.getSettings();
        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
        webSettings.setJavaScriptEnabled(true);// 设置支持javascript脚本

        //如果访问的页面中有Javascript，则webview必须设置支持Javascript
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);


        //在js中调用本地java方法
        mWebView.addJavascriptInterface(new JsInterface(this), "DhccWebView");
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                L.e("lu", "url==" + url);
                loadDialog("正在玩命加载...");
                loadHistoryUrls.add(url);
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadDiss();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                loadDiss();
                loadError("加载失败...");
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType) {
                mUploadMessage = uploadMsg;
                startActivityForResult(createDefaultOpenableIntent(),
                        FILECHOOSER_RESULTCODE);
            }

            // For Android 4.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                startActivityForResult(createDefaultOpenableIntent(),
                        FILECHOOSER_RESULTCODE);

            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     final JsResult result) {
                AlertDialog.Builder b2 = new AlertDialog.Builder(WebViewActivity.this)
                        .setTitle("温馨提示")
                        .setMessage(message)
                        .setPositiveButton("确认",
                                new OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        result.confirm();
                                    }
                                });
                b2.setCancelable(false);
                b2.create();
                b2.show();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(WebViewActivity.this)
                        .setTitle("JsConfirm")
                        .setMessage(message)
                        .setPositiveButton("OK", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .setNegativeButton("Cancel", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.cancel();
                            }
                        })
                        .setCancelable(false)
                        .show();
                return true;
            }
        });
        loadData();
    }

    /**
     * 处理 js 事件
     */
    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        /**
         * 提示
         */
        @JavascriptInterface
        public void showToast(String obj) {
            showInfoToast(obj);
        }
    }

    private void loadData() {
        mWebView.loadUrl("file:///android_asset/" + URL);
    }

    private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "请选择");
        return chooser;
    }

    private Intent createDefaultOpenableIntent() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");

        Intent chooser = createChooserIntent(createCameraIntent());
        chooser.putExtra(Intent.EXTRA_INTENT, i);
        return chooser;
    }

    private Intent createCameraIntent() {
        // 注意：此处代码主要目的是将拍照文件保存在 browser-photos 文件夹下（非系统默认文件夹）
        // 如不需要这样处理，可以简化代码
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File externalDataDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getPath() + "/Images/");
        cameraDataDir.mkdirs();
        mCameraFilePath = cameraDataDir.getPath() + System.currentTimeMillis()
                + ".png";
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(mCameraFilePath)));
        return cameraIntent;
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && loadHistoryUrls.size() > 1) {
            loadHistoryUrls.remove(loadHistoryUrls.size() - 1);
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
